package in.abacritt.android.xclock;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.SystemClock;

public class XClockWidgetProvider extends AppWidgetProvider {

	public static String MY_WIDGET_UPDATE = "XCLOCK_WIDGET_UPDATE";
	public static String MY_WIDGET_WEATHER_UPDATE = "XCLOCK_WIDGET_WEATHER_UPDATE";
	public static String MY_WIDGET_WEATHER_UPDATE_COMP = "XCLOCK_WIDGET_WEATHER_UPDATE_COMP";
	public static String MY_WEATHER_INFO = "XCLOCK_WEATHER_INFO";

	private XClockBroadcastReceiver weatherUpdateReceiver;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {

	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		// TODO Auto-generated method stub
		super.onDeleted(context, appWidgetIds);
	}

	@Override
	public void onDisabled(Context context) {
		// TODO Auto-generated method stub
		super.onDisabled(context);
	}

	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);

		// Register the receivers
		IntentFilter filterWeatherUpdateComp = new IntentFilter(
				XClockWidgetProvider.MY_WIDGET_WEATHER_UPDATE_COMP);
		filterWeatherUpdateComp.addCategory(Intent.CATEGORY_DEFAULT);

		weatherUpdateReceiver = new XClockBroadcastReceiver();

		context.getApplicationContext().registerReceiver(weatherUpdateReceiver,
				filterWeatherUpdateComp);

		Intent msgIntent = new Intent(context, OpenWeatherUpdateService.class);
		context.getApplicationContext().startService(msgIntent);

		Intent intentClock = new Intent(context, XClockBroadcastReceiver.class);
		PendingIntent sender = PendingIntent.getBroadcast(context, 0,
				intentClock, 0);

		// We want the alarm to go off 1 seconds from now.
		long firstTime = SystemClock.elapsedRealtime();
		firstTime += 1000;

		// Schedule the alarm!
		AlarmManager am = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		am.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, 1000, sender);

		// Weather update intent
		Intent intentWeather = new Intent(context,
				XClockBroadcastReceiver.class);
		intentWeather.setAction(MY_WIDGET_WEATHER_UPDATE);
		PendingIntent senderWeather = PendingIntent.getBroadcast(context, 0,
				intentWeather, 0);

		// Schedule the alarm!
		am.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, 60 * 30 * 1000,
				senderWeather);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
	}

}
